import sys, time

class Bar(object):
    """
    自定义进度条，需要传入的参数：
    1. 循环总量total
    2. 单次循环增量step
    使用方法：
    total = 100
    step = 3
    sum1 = 0
    bar = Bar(total, step)
    while sum1 < total:
        sum1 += step
        time.sleep(1)
        bar.next()
    bar.finish()
    """
    bar_prefix = ' ['
    bar_suffix = '] '
    prefix = '%4.2f%%'
    fill = '#'
    empty_fill = ' '
    def __init__(self, total, step, **kwargs):
        super(Bar, self).__init__(**kwargs)
        self.max = total
        self.step = step
        self.index = 0

    @property
    def progress(self):
        return min(1, self.index / self.max) * 100

    def print_info(self):
        # 隐藏光标
        print('\x1b[?25l', end='', flush=True)
        sys.stdout.write('\r')
        prefix = self.prefix % self.progress
        bar = self.fill * int(self.progress)
        empty = self.empty_fill * (100 - int(self.progress))
        info = prefix + self.bar_prefix + bar + empty + self.bar_suffix
        sys.stdout.write(info)
        sys.stdout.flush()

    def next(self):
        self.index = self.index + self.step
        self.print_info()

    def finish(self):
        # 显示光标并换行
        file = sys.stdout
        if file.isatty():
            print('\x1b[?25h', end='', file=file)
        sys.stdout.write('\n')

total = 100
step = 11
sum1 = 0
bar = Bar(total, step)
while sum1 < total:
    sum1 += step
    time.sleep(1)
    bar.next()
bar.finish()
